import storageApi from '../../core/storage/storage';
import BaseController from '../../core/controllers/Base.controller';

@Inject('$log', '$rootScope', 'globalService', 'deviceService', 'ngDialog', 'ngDialogService')
class DeviceInfoController extends BaseController {
  constructor() {
    super();

    this.equipListData = [];

    this.paginationService = this.deviceService;
    this.$setQueryCallback((res) => {
      this.equipListData = res.rows;
    });

    this.mapParams = {
      orgId: $rootScope.orgId || storageApi.get('orgId'),
      // deviceName: '',
      // code: '',
      // inOutStatus: '',
      // sortType: 1,
    };
    this.mapParams.inOutStatus = '';
    this.$paginationQuery();
    // 全选
    this.toggleAllFlag = false;
  }

  $query(param) {
    if (param && param.inTimeMin.$valid && param.inTimeMax.$valid
      && param.inTimeMin.$viewValue > param.inTimeMax.$viewValue) {
      this.ngDialogService.alertError('进场时间开始时间应小于结束时间');
      return;
    }
    this.$paginationQuery();
  }

  // /*eslint-disable */
  // $getDeviceCategory(type) {
  //   // console.log(type, this.deviceName);
  //   if (this.deviceTypeParams) {
  //     this.deviceTypeParams.forEach((item) => {
  //       console.log(item.value, type);
  //       if (item.value === type) {
  //         this.deviceName = item.name;
  //       }
  //     });
  //     return this.deviceName;
  //   }
  // }

  $reset() {
    this.mapParams = {
      orgId: this.$rootScope.orgId || storageApi.get('orgId'),
    };
  }

  $delete(id) {
    this.ngDialogService.confirm('确定删除此数据吗？', id)
      .then((data) => {
        this.$log.debug(data);
        this.deviceService
          .delete([id])
          .then((res) => {
            this.ngDialogService.alertError(res.message);
            this.$paginationQuery();
          }, reason => reason);
      });
  }

  /*eslint-disable */
  $toggleAll() {
    this.equipListData.forEach((item) => {
      item.checked = this.toggleAllFlag;
    });
  }

  // 判断全选设备
  $isChange() {
    let bool = true;
    this.equipListData.forEach((item) => {
      if (!item.checked) {
        bool = false;
      }
    });
    this.toggleAllFlag = bool;
  }

  // 获取选中设备
  $getSelectedEquip() {
    let selectedEquipList = [];
    if (this.equipListData) {
      let length = this.equipListData.length;
      for (let i = 0; i < length; i++) {
        let item = this.equipListData[i];
        if (item.checked) {
          selectedEquipList.push(item);
        }
      }
    }
    return selectedEquipList;
  }

  // 进场登记
  $intoRegistration(sysCtrl) {
    let ids = [], outTime = [];
    let selectedEquipList = this.$getSelectedEquip();
    let deviceStatusCheck = true;
    let dialogPrompt = '';
    if (!selectedEquipList.length) {
      this.ngDialogService.alertError('请选择设备');
      return;
    };
    selectedEquipList.forEach((item) => {
      if (item.inOutStatus === '1') {
        dialogPrompt +=`${item.deviceName}[${item.code}]\n`;
        deviceStatusCheck = false;
      } else {
        ids.push(item.id);
        outTime.push(item.outTime);
      }
    });
    if (deviceStatusCheck) {
      this.ngDialog.open({
        template: 'paEquipIntoRegistrationDialog',
        className: 'ngdialog-theme-default pa-in-out-registration',
        controllerAs: 'vm',
        controller($scope, ngDialogService) {
          'ngInject';

          const max = _.max(outTime);
          const date = new Date(parseInt(max));
          this.month = date.getMonth() + 1;
          this.day = date.getDate();
          if (this.month < 10) {
            this.month = '0' + this.month;
          }
          if (this.day < 10) {
            this.day = '0' + this.day;
          }
          const timeStr = date.getFullYear() + '-' + this.month + '-' + this.day;

          this.sureBtnFn = () => {
            if (this.recordTime < timeStr) {
              ngDialogService.alertError('进场时间应该大于出场时间');
              return false;
            }
            const reqData = {
              deviceIds : ids,
              recordTime : this.recordTime,
            };
            sysCtrl.deviceService
              .saveInTime(reqData)
              .then((res) => {
                sysCtrl.$paginationQuery();
                ngDialogService.alertSuccess(res.message);
                sysCtrl.toggleAllFlag = false;
              });
            $scope.closeThisDialog();
          };
        },
      });
    } else {
      this.ngDialogService.alertError(`${dialogPrompt}已在场，请重新选择`);
      return;
    }
  }

  // 离场登记
  $outRegistration(sysCtrl) {
    let ids = [], inTime = [];
    let selectedEquipList = this.$getSelectedEquip();
    let deviceStatusCheck = true;
    let dialogPrompt = '';
    if (!selectedEquipList.length) {
      this.ngDialogService.alertError('请选择设备');
      return;
    };
    selectedEquipList.forEach((item) => {
      if (item.inOutStatus === '2') {
        dialogPrompt +=`${item.deviceName}[${item.code}]\n`;
        deviceStatusCheck = false;
      } else {
        ids.push(item.id);
        inTime.push(item.inTime);
      }
    });
    if (deviceStatusCheck) {
      this.ngDialog.open({
        template: 'paEquipOutRegistrationDialog',
        className: 'ngdialog-theme-default pa-in-out-registration',
        controllerAs: 'vm',
        controller($scope, ngDialogService) {
          'ngInject';

          const max = _.max(inTime);
          const date = new Date(parseInt(max));
          this.month = date.getMonth() + 1;
          this.day = date.getDate();
          if (this.month < 10) {
            this.month = '0' + this.month;
          }
          if (this.day < 10) {
            this.day = '0' + this.day;
          }
          const timeStr = date.getFullYear() + '-' + this.month + '-' + this.day;
          this.sureBtnFn = () => {
            if (this.recordTime < timeStr) {
              ngDialogService.alertError('出场时间应该大于进场时间');
              return false;
            }
            const reqData = {
              deviceIds : ids,
              recordTime : this.recordTime,
            };
            sysCtrl.deviceService
              .saveOutTime(reqData)
              .then((res) => {
                sysCtrl.$paginationQuery();
                ngDialogService.alertSuccess(res.message);
                sysCtrl.toggleAllFlag = false;
              });
            $scope.closeThisDialog();
          };
        },
      });
    } else {
      this.ngDialogService.alertError(`${dialogPrompt}已离场，请 重新选择`);
      return;
    }
  }

  // 打印二维码
  $printQrCode(sysCtrl) {
    let selectedEquipList = this.$getSelectedEquip();
    if (!selectedEquipList.length) {
      this.ngDialogService.alertError('请选择设备');
      return;
    }
    this.selectedEquipList = selectedEquipList;
    this.ngDialog.open({
      template: 'equipInfoQrCodePrintDialog',
      className: 'ngdialog-theme-default pa-in-out-registration',
      controllerAs: 'vm',
      controller($scope) {
        'ngInject';

        this.selectedEquipList = sysCtrl.selectedEquipList;

        this.print = () => {
          $('.qr-print').print({ globalStyles: false, timeout: 1200 });
        }

        this.getQrCodeSrc = (item) => {
          let codeJson = {
            id: item.id,
            type: 2, // 1:人员、设备
          }
          codeJson = JSON.stringify(codeJson);
          let qrContent = encodeURIComponent(codeJson);
          let requestUrlStr = `/sgms/api/v1/common/qr?size=160&code=${qrContent}`;
          return requestUrlStr;
        }
      },
    });
  }
}

export default DeviceInfoController;
